﻿// This file is part of WifiCC3100 - the Managed Wifi Driver for the TI CC3100
// Hosted on Codeplex: http://cc3100.codeplex.com
// WifiCC3100 is free software licensed under the Apache License 2.0
// © Copyright 2014 ValkyrieTech, LLC

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace UniFlashCompanion
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        ObservableCollection<FileInfoWithCheck> files = new ObservableCollection<FileInfoWithCheck>();

        public MainWindow()
        {
            InitializeComponent();

            dtgFiles.ItemsSource = files;

            files.CollectionChanged += files_CollectionChanged;
            lblSelectionSize.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
        }

        void files_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            lblSelectionSize.Content = "Total Selection Size: " + files.Where(f => f.IsChecked).Sum(x => x.Info.Length) + " bytes";
        }

        private void txtLocalRoot_Drop(object sender, DragEventArgs e)
        {
           
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
 
                if (Directory.Exists(files[0]))
                {
                    txtLocalRoot.Text = files[0];
                }
            }
        }

        private void txtLocalRoot_PreviewDragOver(object sender, DragEventArgs e)
        {
            e.Handled = true;

            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effects = DragDropEffects.Move;
            }
            else
            {
                e.Effects = DragDropEffects.None;
            }
        }

        private void btnFill_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtLocalRoot.Text) || Directory.Exists(txtLocalRoot.Text) == false)
            {
                MessageBox.Show("Invalid Local Root specified.  Must be a directory.  ");
                return;
            }

            var d = new DirectoryInfo(txtLocalRoot.Text);

            files.Clear();

            foreach (var f in d.EnumerateFiles("*", SearchOption.AllDirectories).Where(x => x.Name != "CC3xxx_token.xml" && x.Name != "CC3xxx_template.xml"))
            {
                files.Add(new FileInfoWithCheck() { Info = f, IsChecked = (f.Extension == ".html" || f.Extension == ".js" || f.Extension == ".css" || f.Extension == ".jgz" || f.Extension == ".cgz" || f.Extension == ".json" || f.Extension == ".xml" || f.Extension == ".htm" || f.Extension == ".jpg" || f.Extension == ".gif" || f.Extension == ".png"), FlashPath = (txtFlashRoot.Text.TrimEnd('\\') + @"/" + f.FullName.Substring(txtLocalRoot.Text.Length).TrimStart('\\').Replace('\\', '/')) });
            }
        }

        private void dtgFiles_Drop(object sender, DragEventArgs e)
        {
            txtLocalRoot_Drop(sender, e);
            btnFill_Click(sender, null);
        }

        private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnGenerate_Click(object sender, RoutedEventArgs e)
        {
            this.IsEnabled = false;

            string ucfName = "AutoGenerated";
            
            string ucfContent = File.ReadAllText("base.ucf");
            ucfContent = ucfContent.Replace("<COM_PORT/>", txtComPort.Text);

            File.Delete(System.IO.Path.Combine(txtLocalRoot.Text, ucfName + ".ucf"));
            File.WriteAllText(System.IO.Path.Combine(txtLocalRoot.Text, ucfName + ".ucf"), ucfContent);

            var sessionDir = Directory.CreateDirectory(System.IO.Path.Combine(txtLocalRoot.Text, ucfName + "_session"));

            var templateDir = sessionDir.CreateSubdirectory("templates");
           
            var tokenFileContent = new StringBuilder();
            
            foreach (var aFile in files.Where(f => f.IsChecked))
            {
                tokenFileContent.Append("<Filename name=\"" + aFile.FlashPath + "\">\n<MAX>0x0</MAX>\n<RW>0x0</RW>\n<RO>0x0</RO>\n</Filename>");
            }

            string tokenContent = File.ReadAllText("CC3xxx_token.xml");

            tokenContent = tokenContent.Replace("<INSERT_FILES_HERE/>", tokenFileContent.ToString());

            File.WriteAllText(System.IO.Path.Combine(templateDir.FullName, "CC3xxx_token.xml"), tokenContent);


            var templateFileContent = new StringBuilder();

            foreach (var aFile in files.Where(f => f.IsChecked))
            {
                templateFileContent.Append(templateFileBase.Replace("!FLASH_PATH", aFile.FlashPath).Replace("!LOCAL_PATH", aFile.Info.FullName));
            }

            string templateContent = File.ReadAllText("CC3xxx_template.xml");

            templateContent = templateContent.Replace("<INSERT_FILES_HERE/>", templateFileContent.ToString());

            File.WriteAllText(System.IO.Path.Combine(templateDir.FullName, "CC3xxx_template.xml"), templateContent);

            this.IsEnabled = true;


            var response = MessageBox.Show(this, ("You new UCF file for use in UniFlash is located here: " + System.IO.Path.Combine(txtLocalRoot.Text, ucfName + ".ucf") + "\n Copy this location to the clipboard? "), "Copy Path to Clipboard?", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (response == MessageBoxResult.Yes) Clipboard.SetText(System.IO.Path.Combine(txtLocalRoot.Text, ucfName + ".ucf"));

        }

        private static string templateFileBase = "<Filename name=\"!FLASH_PATH\" category=\"user\">" +
                                                 "\r\n      <Version>0</Version>" + 
                                                 "\r\n      <Type>blob</Type>" + 
                                                 "\r\n      <Storage>SFLASH</Storage>" + 
                                                 "\r\n      <MaxSize>0</MaxSize>" + 
                                                 "\r\n      <url>!LOCAL_PATH</url>" + 
                                                 "\r\n      <mode>" + 
                                                 "\r\n         <ModeEntry name=\"Rollback\" checked=\"false\"/>" + 
                                                 "\r\n         <ModeEntry name=\"Secured\" checked=\"false\"/>" + 
                                                 "\r\n         <ModeEntry name=\"NoSignatureTest\" checked=\"false\"/>" + 
                                                 "\r\n         <ModeEntry name=\"StaticToken\" checked=\"false\"/>" + 
                                                 "\r\n         <ModeEntry name=\"VendorToken\" checked=\"false\"/>" + 
                                                 "\r\n         <ModeEntry name=\"PublicWrite\" checked=\"false\"/>" + 
                                                 "\r\n         <ModeEntry name=\"PublicRead\" checked=\"false\"/>" + 
                                                 "\r\n      </mode>" + 
                                                 "\r\n      <verify>true</verify>" + 
                                                 "\r\n      <Update>true</Update>" + 
                                                 "\r\n      <Erase>true</Erase>" + 
                                                 "\r\n      <Certificate></Certificate>" +
                                                 "\r\n      <Signature></Signature>" + 
                                                 "\r\n   </Filename>" + 
                                                 "\r\n";




        private void CheckBox_Changed(object sender, RoutedEventArgs e)
        {
            files_CollectionChanged(null, null);

        }


    }

    public partial class FileInfoWithCheck
    {
        public FileInfo Info { get; set; }

        public bool IsChecked { get; set; }

        public string FlashPath { get; set; }

    }

}
